package com.jason.cloud.engine.share.driver.user.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jason.cloud.engine.share.driver.email.bean.EmailBean;
import com.jason.cloud.engine.share.driver.email.service.EmailService;
import com.jason.cloud.engine.share.driver.enterprise.bean.EnterpriseBean;
import com.jason.cloud.engine.share.driver.enterprise.service.EnterpriseService;
import com.jason.cloud.engine.share.driver.enterprise.util.EnterpriseUtil;
import com.jason.cloud.engine.share.driver.grant.bean.GrantBean;
import com.jason.cloud.engine.share.driver.grant.service.GrantService;
import com.jason.cloud.engine.share.driver.pack.bean.PackBean;
import com.jason.cloud.engine.share.driver.pack.service.PackService;
import com.jason.cloud.engine.share.driver.role.bean.RoleBean;
import com.jason.cloud.engine.share.driver.role.service.RoleService;
import com.jason.cloud.engine.share.driver.user.bean.UserBean;
import com.jason.cloud.engine.share.driver.user.service.UserService;
import com.jason.cloud.engine.share.driver.user.util.UserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Resource
    private UserService userService;

    @Resource
    private PackService packService;

    @Resource
    private RoleService roleService;

    @Resource
    private EnterpriseService enterpriseService;

    @Resource
    private EmailService emailService;

    @Resource
    private GrantService grantService;

    /**
     * 加载
     * @param id
     * @return
     */
    @RequestMapping(value = "/query/{id}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public @ResponseBody JSONObject queryUserById(@PathVariable String id) {
        UserBean userBean = this.userService.queryUserById(id);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("stat", "success");
        jsonObject.put("msg", "");
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("id", userBean.getId());
        jsonObject1.put("name", userBean.getName());
        jsonObject.put("data", jsonObject1);
        System.out.println("JSON " + jsonObject.toJSONString());
        return jsonObject;
    }

    /**
     * 注册
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public @ResponseBody JSONObject register(@RequestBody JSONObject json) {
        JSONObject jsonObject = new JSONObject();
        String company = json.getString("company");
        String name = json.getString("name");
        String email = json.getString("email");
        String tel = json.getString("tel");

        PackBean packBean = new PackBean();
        RoleBean roleBean = new RoleBean();
        UserBean userBean = new UserBean();
        EnterpriseBean enterpriseBean = new EnterpriseBean();

        //验证手机号是否注册
        int status_count = 0;
        boolean repeatTel = false;
        int count_tel = this.userService.existTel(tel);
        if (count_tel > 0) {
            status_count = status_count + 1;
            repeatTel = true;
        }

        //验证邮箱是否注册
        boolean repeatEmail = false;
        int count_email = this.userService.existEmail(email);
        if (count_email > 0) {
            status_count = status_count + 1;
            repeatEmail = true;
        }

        if(status_count == 0) {
            //拉取默认套餐、创建企业
            packBean = this.packService.queryDefaultPackByIsDefault();
            if (packBean != null) {
                enterpriseBean.setName(company);
                enterpriseBean.setPackId(packBean.getId());
                enterpriseBean.setRegisterDate(new Date());
                enterpriseBean.setBeginDate(new Date());
                enterpriseBean.setEndDate(EnterpriseUtil.generateBillExpireDate(1));
                this.enterpriseService.insertEnterprise(enterpriseBean);
            }

            //拷贝系统默认角色
            this.roleService.copyEnterpriseRoleByDefault(enterpriseBean.getId());

            //获取企业的默认角色
            roleBean = this.roleService.queryDefaultRoleByEnterpriseId(enterpriseBean.getId());

            //拷贝默认授权
            this.grantService.copyRoleGrantByRoleId(roleBean.getId().trim());

            //设置注册用户参数
            userBean.setName(name);
            String generateUserPassword = UserUtil.generateUserPassword();
            userBean.setPassword(generateUserPassword);
            userBean.setEmail(email);
            userBean.setTel(tel);
            userBean.setStatus(true);
            userBean.setRegister(new Date());
            userBean.setRoleId(roleBean.getId());
            userBean.setEnterpriseId(enterpriseBean.getId());

            //保存
            this.userService.insertUser(userBean);

            //发送邮件
            this.emailService.sendEmailByServer("[云引擎服务] 你的账户已注册成功，请等待管理员审核。", email, "", "账户名称 : " + email + " , 登录密码为 : " + generateUserPassword);

            //返回时数据
            jsonObject.put("status", "200");
            jsonObject.put("msg", "注册成功、跳转到登录页面");
        } else {
            if(repeatTel) {
                jsonObject.put("status", "201");
                jsonObject.put("msg", "已被注册、请使用其他手机号");
            }
            if(repeatEmail) {
                jsonObject.put("status", "202");
                jsonObject.put("msg", "已被注册、请使用其他邮箱");
            }
        }
        return jsonObject;
    }


    /**
     * 登录
     * @param userBean
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public @ResponseBody JSONObject login(@RequestBody UserBean userBean, HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        UserBean item = this.userService.queryUserByLoginName(userBean.getName());
        if (item == null) {
            jsonObject.put("status", 201);
            jsonObject.put("msg", "用户不存在");
        } else {
            if (!userBean.getPassword().equals(item.getPassword())) {
                jsonObject.put("status", 202);
                jsonObject.put("msg", "密码不正确");
            } else {
                jsonObject.put("status", 200);
                request.getSession().setAttribute("item", item);
            }
        }
        return jsonObject;
    }

    /**
     * 退出
     * @param id
     * @return
     */
    @RequestMapping(value = "/logout/{id}", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    public @ResponseBody JSONObject logout(@PathVariable String id, HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        HttpSession session = request.getSession();
        if (session.getAttribute("item") != null) {
            UserBean item = (UserBean)session.getAttribute("item");
            if (id.equals(item.getPassword())) {
                session.removeAttribute("item");
                jsonObject.put("status", "200");
                jsonObject.put("msg", "");
            }
        }
        return jsonObject;
    }

    /**
     * 找密
     * @return
     */
    @RequestMapping(value = "/forget", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
    public @ResponseBody JSONObject forgetPasswordByEmail(@RequestBody JSONObject json) {

        //获取邮箱
        String email = json.getString("email");

        //生成新秘钥
        String generateUserPassword = UserUtil.generateUserPassword();

        //返回值
        JSONObject jsonObject = new JSONObject();

        //加载
        UserBean userBean = this.userService.queryUserByLoginName(email);
        if (userBean == null) {
            jsonObject.put("status", "201");
            jsonObject.put("msg", "此邮箱不存在、请检查后再试");
        } else {
            //设置新秘钥
            userBean.setPassword(generateUserPassword);

            //更新后台数据库
            this.userService.forgetPasswordByEmail(userBean);

            //发送邮件
            this.emailService.sendEmailByServer("[云引擎服务] 你的账户密码找回成功，请使用新密码登录。", email, "", "账户名称 : " + email + " , 登录密码为 : " + generateUserPassword);

            //实体转换成JSON对象
            jsonObject.put("status", "200");
            jsonObject.put("msg", "密码找回成功");
        }

        return jsonObject;
    }

    /**
     * 列举
     * @return
     */
    @RequestMapping(value = "/all", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public @ResponseBody JSONObject getUserLimitByEnterpriseId(@RequestParam int page, @RequestParam int limit, @RequestParam String enterpriseId) {

        //加载所有
        List<UserBean> userBeanList = this.userService.getUserLimitByEnterpriseId((page - 1 ) * limit, limit, enterpriseId.trim());
        int count = this.userService.getUserCountByEnterpriseId(enterpriseId);

        //返回值
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "");
        jsonObject.put("count", count);

        //遍历数据
        JSONArray jsonArrayUser = new JSONArray();
        UserBean userBean = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        RoleBean roleBean = null;
        for(Iterator itr = userBeanList.iterator(); itr.hasNext();) {
            userBean = (UserBean)itr.next();
            JSONObject json = new JSONObject();
            json.put("id", userBean.getId());
            json.put("name", userBean.getName());
            json.put("email", userBean.getEmail());
            json.put("tel", userBean.getTel());
            json.put("status", userBean.isStatus()?"可用":"--");
            json.put("register", simpleDateFormat.format(userBean.getRegister()));
            json.put("lastLogin", userBean.getLastLogin() == null?"--":simpleDateFormat.format(userBean.getLastLogin()));
            roleBean = this.roleService.queryRoleById(userBean.getRoleId().trim());
            json.put("roleId", roleBean.getName());
            jsonArrayUser.add(json);
        }
        jsonObject.put("data", jsonArrayUser);
        return jsonObject;
    }


    /**
     * 账户开通
     * @param json
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public @ResponseBody JSONObject insertUser(@RequestBody JSONObject json) {
        JSONObject jsonObject = new JSONObject();
        String name = json.getString("name");
        String email = json.getString("email");
        String tel = json.getString("tel");
        String roleId = json.getString("roleId");
        String enterpriseId = json.getString("enterpriseId");

        UserBean userBean;

        //验证手机号是否注册
        int status_count = 0;
        boolean repeatTel = false;
        int count_tel = this.userService.existTel(tel);
        if (count_tel > 0) {
            status_count = status_count + 1;
            repeatTel = true;
        }

        //验证邮箱是否注册
        boolean repeatEmail = false;
        int count_email = this.userService.existEmail(email);
        if (count_email > 0) {
            status_count = status_count + 1;
            repeatEmail = true;
        }

        if(status_count == 0) {
            //企业对象
            EnterpriseBean enterpriseBean = this.enterpriseService.queryEnterpriseById(enterpriseId.trim());

            //角色对象
            RoleBean roleBean = this.roleService.queryRoleById(roleId.trim());

            //设置注册用户参数
            userBean = new UserBean();

            userBean.setName(name);
            String generateUserPassword = UserUtil.generateUserPassword();
            userBean.setPassword(generateUserPassword);
            userBean.setEmail(email);
            userBean.setTel(tel);
            userBean.setStatus(true);
            userBean.setRegister(new Date());
            userBean.setRoleId(roleBean.getId());
            userBean.setEnterpriseId(enterpriseBean.getId());

            //保存
            this.userService.insertUser(userBean);

            //发送邮件
            this.emailService.sendEmailByServer("[云引擎服务] 你的账户已开通成功。", email, "", "账户名称 : " + email + " , 登录密码为 : " + generateUserPassword);

            //返回时数据
            jsonObject.put("status", "200");
            jsonObject.put("msg", "账户开通成功");
        } else {
            if(repeatTel) {
                jsonObject.put("status", "201");
                jsonObject.put("msg", "该手机号已被使用");
            }
            if(repeatEmail) {
                jsonObject.put("status", "202");
                jsonObject.put("msg", "该邮箱已被使用");
            }
        }
        return jsonObject;
    }

    /**
     * 用户禁用
     * @param paramStr
     * @return
     */
    @RequestMapping(value = "/disabled", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
    public @ResponseBody JSONObject disabledUser(@RequestBody String paramStr) {
        //取值
        JSONArray jsonArray = JSON.parseArray(paramStr);

        //处理
        JSONObject jsonObject = null;
        for(int i = 0; i < jsonArray.size(); i++) {
            jsonObject = jsonArray.getJSONObject(i);
            String id = jsonObject.getString("id").trim();

            //更新
            UserBean userBean = this.userService.queryUserById(id);
            userBean.setStatus(false);
            this.userService.updateUserParamById(userBean);
        }

        //返回值
        jsonObject = new JSONObject();
        jsonObject.put("status", 200);
        jsonObject.put("msg", "用户禁用成功");

        return jsonObject;
    }

    /**
     * 用户启用
     * @param paramStr
     * @return
     */
    @RequestMapping(value = "/enabled", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
    public @ResponseBody JSONObject enabledUser(@RequestBody String paramStr) {
        //取值
        JSONArray jsonArray = JSON.parseArray(paramStr);

        //处理
        JSONObject jsonObject = null;
        for(int i = 0; i < jsonArray.size(); i++) {
            jsonObject = jsonArray.getJSONObject(i);
            String id = jsonObject.getString("id").trim();

            //更新
            UserBean userBean = this.userService.queryUserById(id);
            userBean.setStatus(true);
            this.userService.updateUserParamById(userBean);
        }

        //返回值
        jsonObject = new JSONObject();
        jsonObject.put("status", 200);
        jsonObject.put("msg", "用户启用成功");

        return jsonObject;
    }

    /**
     * 检查用户配额数
     * @param enterpriseId
     * @return
     */
    @RequestMapping(value = "/checkUserQuota/{enterpriseId}", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    public @ResponseBody JSONObject checkUserQuota(@PathVariable String enterpriseId) {
        JSONObject jsonObject = new JSONObject();

        //获取企业对象
        EnterpriseBean enterpriseBean = this.enterpriseService.queryEnterpriseById(enterpriseId.trim());

        //获取资费对象
        PackBean packBean = this.packService.queryPackById(enterpriseBean.getPackId().trim());
        int count_user_quota = packBean.getUsers();

        //计数用户
        int count = this.userService.getUserCountByEnterpriseId(enterpriseId.trim());

        System.out.println(" == " + count + "　　"  +  count_user_quota);


        if (count < count_user_quota) {
            jsonObject.put("status", 200);
            jsonObject.put("msg", "");
        } else {
            jsonObject.put("status", 201);
            jsonObject.put("msg", "企业用户配额已用完、请联系管理员。");
        }
        return jsonObject;
    }
}
